package com.lsy.weizhi2.picture;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;


import com.lsy.weizhi2.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class PictureActivity extends Activity {

    private IWxCallback mCallback;
    private static final int PHOTO_REQUEST_ALBUM = 1;
    boolean falg = true;
    private ImageList adapter;
    private GridView photoalbum;
    private Context context;

    List<String> list;
    List<Bitmap> listB = new ArrayList<Bitmap>();
    List<Map<String,String>>  listtemp =  new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context=PictureActivity.this;
        list = getSD();
        imageBitmap();
        Intent intent = getIntent();
        if (intent != null){
            mCallback = PictureUtils.getCallback();
            int op = intent.getIntExtra(PictureUtils.OPERATION, -1);
            if (op == PictureUtils.ALBUM){
                getPictureFromAlbum();
            }
        }
    }

    private void getPictureFromAlbum(){
       /* Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image*//*");*/
        Intent intent = new Intent(context, MyAblum.class);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_ALBUM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_ALBUM && data != null){
           /* Uri uri = data.getData();
            String path = getFilePathFromUri(uri);*/
            String path=data.getStringExtra("image");
            Log.i("PictureUtils","path==="+path);
            if (mCallback != null){
                mCallback.onSuccess(path);

            }
        }
        finish();
    }

    private String getFilePathFromUri(Uri uri){
        String filePath = uri.toString();
        //红米Note这里会直接返回文件路径，因此这里需要适配一下(红米Note返回的数据格式为：file:///storage/emulated/0/.....)
        if (!TextUtils.isEmpty(filePath) && filePath.startsWith("file:")){
            filePath = filePath.substring(7);
            return filePath;
        }
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        try {
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
        } finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return filePath;
    }
    public class ImageList extends BaseAdapter {
        private Context context;

        public ImageList(Context a) {
            this.context = a;
        }

        @Override
        public int getCount() {
            return listB.size();
        }

        @Override
        public Object getItem(int position) {
            return listB.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView iv = new ImageView(context);
            iv.setImageBitmap( listB.get(position));
            if(listtemp.size()>0){
                for (int i = 0; i < listtemp.size(); i++) {
                    if(Integer.valueOf((listtemp.get(i).get("id")))==position){
                        Bitmap newb = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher );
                        Bitmap src = adapter.getcheckedImageIDPostion(position);
                        Bitmap bi = Bitmap.createBitmap( listB.get(position).getWidth(), listB.get(position).getHeight(), Bitmap.Config.ARGB_8888 );
                        Canvas cv = new Canvas( bi );
                        cv.drawBitmap( src, 2, 0, null );
                        cv.drawBitmap( newb, listB.get(position).getWidth() - newb.getWidth() -5, listB.get(position).getHeight() - newb.getHeight() -5, null );//在src的右下角画入水印
                        cv.save( Canvas.ALL_SAVE_FLAG );//保存
                        cv.restore();//存储
                        ((ImageView)iv).setImageBitmap(bi);
                    }
                }
            }
            iv.setAdjustViewBounds(true);
            return iv;
        }
        /* 自定义获取对应位置的图片ID */

        public Bitmap getcheckedImageIDPostion(int i) {

            return listB.get(i);

        }
    }


    private void imageBitmap(){

        new Thread() {
            @Override
            public void run() {

                //List list01 = new ArrayList();
                Bitmap bitmap;

                for (int i = 0; i < list.size(); i++) {

                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(list.get(i), opts);

                    opts.inJustDecodeBounds = false;

                    Bitmap bmp = BitmapFactory.decodeFile(list.get(i), opts);


                }
                Message message = new Message();
                message.what = 1;
                handler0.sendMessage(message);
            }
        }.start();


    }
    private Handler handler0 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    adapter = new ImageList(context);
                   // photoalbum.setAdapter(adapter);
                    break;
                case -1:
                    break;
            }
        };
    };
    /**
     *
     * @return
     */
    private List<String> getSD() {
        /* 设定目前所在路径 */
        List<String> it = new ArrayList<String>();
        //File f = new File(path.getPath() );

        return it;
    }

    private boolean getImageFile(String fName) {
        boolean re;

        /* 取得扩展名 */
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();

        /* 按扩展名的类型决定MimeType */
        if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            re = true;
        } else {
            re = false;
        }
        return re;
    }
}
